import { useDeviceMode } from "@/hooks/useDeviceMode";
import { PrismaClient } from "@prisma/client";
import CryptoJS from "crypto-js";
import styles from "@/styles/search.module.scss";
import Link from "next/link";
import LottieView from "@/components/LottieView";
import NothingLottieJson from "@/public/lottie/nothing.lottie.json";
import Cookies from "cookies";
import Head from "next/head";

interface Item {
  id: string;
  user: {
    name: string;
  };
  title: string;
  createdAt: string;
}

interface Data {
  year: string;
  list: Item[];
}
interface SearchPageProps {
  list: Data[];
}

const SearchPage = (props: SearchPageProps) => {
  const mobile = useDeviceMode();

  return (
    <>
      <Head>
        <title>所有记录</title>
        <meta name="keywords" content="记录,博客,文章,日记,随笔"></meta>
      </Head>
      {!props.list.length && (
        <div className="flex flex-col items-center p-10">
          <LottieView
            animationData={NothingLottieJson}
            stopFrame={10}
            loop={false}
          ></LottieView>
          <div>暂无数据</div>
        </div>
      )}
      <div className={mobile ? styles.mobile : styles.pc}>
        <div className={styles.container}>
          {props.list.map((item) => {
            return (
              <div className={styles.box} key={item.year}>
                <div className={styles.year}>{item.year}</div>
                <ol>
                  {item.list.map((item) => {
                    return (
                      <li
                        title={item.user.name}
                        className={styles.title}
                        key={item.id}
                      >
                        <Link href={"/article/" + item.id}>
                          {item.title}
                          <span style={{ color: "#999" }}>
                            @{item.user.name}
                          </span>
                        </Link>
                      </li>
                    );
                  })}
                </ol>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

export async function getServerSideProps({
  query,
  req,
  res,
}: {
  req: any;
  res: any;
  query: { q: string | undefined };
}) {
  let querystring: string | undefined;
  if (query.q) {
    querystring = query.q;
  }

  const cookier = new Cookies(req, res);
  const userEncoded = decodeURIComponent(
    decodeURIComponent(cookier.get("user") as string)
  );

  const prisma = new PrismaClient();
  const data = await prisma.article.findMany({
    where: {
      title: {
        contains: querystring || "",
      },
      OR: [
        {
          public: true,
        },
        {
          userId: JSON.parse(userEncoded).id,
        },
      ],
    },
    select: {
      id: true,
      title: true,
      year: true,
      createdAt: true,
      user: {
        select: {
          name: true,
        },
      },
    },
    orderBy: {
      year: "desc",
    },
  });

  type Years = {
    year: number;
    list: Item[];
  };

  const years: Years[] = [];

  data.forEach((item) => {
    const listOfYear = years.find((i) => i.year === item.year);
    if (listOfYear) {
      let list = listOfYear.list ? listOfYear.list : [];
      list.push(JSON.parse(JSON.stringify(item)));
      listOfYear.list = list;
    } else {
      years.push({
        year: item.year,
        list: [JSON.parse(JSON.stringify(item))],
      });
    }
  });

  return {
    props: {
      list: years,
    },
  };
}

export default SearchPage;
